package com.changyou.kf.core.listener;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.boot.logging.LoggingSystemProperty;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationStartingEvent) {
            System.out.println("执行：ApplicationStarting");
            return;
        }
        //确定springboot应用使用的Environment且context创建之前发送这个事件
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            System.out.println("执行：ApplicationEnvironmentPrepared");

            String applicationName = System.getProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName());
            String pid = System.getProperty(LoggingSystemProperty.PID.getEnvironmentVariableName());

            System.out.println("ApplicationEnvironmentPrepared applicationName:" + applicationName);
            System.out.println("ApplicationEnvironmentPrepared pid:" + pid);
            return;
        }
        //context已经创建且没有refresh发送个事件
        if (event instanceof ApplicationPreparedEvent) {
            System.out.println("执行：ApplicationPrepared");
            return;
        }
        //context已经refresh且application and command-line runners（如果有） 调用之前发送这个事件
        if (event instanceof ApplicationStartedEvent) {
            System.out.println("执行：ApplicationStarted");
            return;
        }
        //application and command-line runners （如果有）执行完后发送这个事件，此时应用已经启动完毕
        if (event instanceof ApplicationReadyEvent) {
            System.out.println("执行：ApplicationReadyEvent");
            return;
        }
        //应用启动失败后产生这个事件
        if (event instanceof ApplicationFailedEvent) {
            System.out.println("执行：ApplicationFailed");
            System.out.println("==================ApplicationFailed==================");
            return;
        }
    }

}
